package com.bsoft.gol.hbs.message.messageHandle;

import hcn.service.base.sendMsg.MessageHandleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @description: 消息处理服务工厂
 * @author: zhengcb10708
 * @create: 2020-09-28 13:36
 **/
public class MessageHandleServiceFactory {

    //存储消息处理服务实现的实例
    private final static List<MessageHandleService> MESSAGE_HANDLE_SERVICE_IMPL_LIST = new LinkedList<>();
    //消息处理实现和businessType的对应关系-缓存
    private final static Map<String, MessageHandleService> MESSAGE_HANDLE_SERVICE_IMPL_CACHE =
            new ConcurrentHashMap<>(512);
    private final static Logger logger = LoggerFactory.getLogger(MessageHandleServiceFactory.class);


    static {
        /**
         * 初始化消息处理服务实现实例的存储List
         */
        logger.info("MessageHandleServiceFactory init start");
        WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
        String[] beanNamesForType = webApplicationContext.getBeanNamesForType(MessageHandleService.class);
        if (beanNamesForType != null && beanNamesForType.length > 0) {
            for (String beanName :
                    beanNamesForType) {
                MESSAGE_HANDLE_SERVICE_IMPL_LIST.add((MessageHandleService) webApplicationContext.getBean(beanName));
            }
        }
        logger.info("MessageHandleServiceFactory init finish");
    }

    /**
     * @Describe:
     * @Param: [businessType]
     * @Return: hcn.service.base.sendMsg.MessageHandleService
     * @Author: zhengcb10708
     * @Date: 2020/9/28 13:39
     */
    public final static MessageHandleService getResolver(String notificateType) {
        //目前这里采用默认的实现类
        MessageHandleService result = MESSAGE_HANDLE_SERVICE_IMPL_CACHE.get(notificateType);
        if (result == null) {
            for (MessageHandleService messageHandleService : MESSAGE_HANDLE_SERVICE_IMPL_LIST) {
                if (messageHandleService.isMapping(notificateType)) {
                    result = messageHandleService;
                    MESSAGE_HANDLE_SERVICE_IMPL_CACHE.put(notificateType, result);
                    break;
                }
            }
        }
        if (result == null) {
            //如果还是没有匹配上的话，给默认的实现类
            for (MessageHandleService messageHandleService : MESSAGE_HANDLE_SERVICE_IMPL_LIST) {
                if (messageHandleService.isDefault()) {
                    result = messageHandleService;
                    MESSAGE_HANDLE_SERVICE_IMPL_CACHE.put(notificateType, result);
                    break;
                }
            }
        }
        return result;
    }

}
